package com.ji.client;

import com.ji.AbstractPeer;
import com.ji.server.ProtocolDecoder;
import com.ji.server.ProtocolEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

/**
 * Title:
 * Description:
 * Author:吉
 * Since:2017/5/19
 * Version:1.1.0
 */
public class EchoClient implements AbstractPeer {
    private EventLoopGroup group;

    @Override
    public void open() {
        group = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        b.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(
//                                new ObjectEncoder(),
//                                new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                                new ProtocolEncoder(),
                                new ProtocolDecoder(),
                                new EchoClientHandler()
//                                new IdleStateHandler(25, 15, 10, TimeUnit.SECONDS)
                        );
                    }
                });
        // Start the client.
        ChannelFuture f = null;
        try {
            f = b.connect("127.0.0.1", 8007).sync();
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("closed client");
    }

    @Override
    public void close() {
        group.shutdownGracefully();
    }

    public static void main(String[] args) {
        EchoClient client = new EchoClient();
        client.open();
    }
}
